package com.vframework.config.security;

import com.utils.ResponseUtil;
import com.vframework.common.response.R;
import com.vframework.common.response.enums.ReturnEnum;
import com.vframework.filter.TokenFilter;
import com.vframework.system.token.entity.Token;
import com.vframework.system.token.service.TokenService;
import com.vframework.system.user.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * spring security处理器
 *
 * @author shanzhitong
 */
@Configuration
public class SecurityHandlerConfig {

    @Autowired
    private TokenService tokenService;

    /**
     * 登陆成功，返回Token
     *
     * @return
     */
    @Bean
    public AuthenticationSuccessHandler loginSuccessHandler() {
        AuthenticationSuccessHandler successHandler = (HttpServletRequest request, HttpServletResponse response, Authentication authentication) -> {
            SysUser loginUser = (SysUser) authentication.getPrincipal();

            Token token = tokenService.saveToken(loginUser);
            ResponseUtil.responseJson(response, HttpStatus.OK.value(), R.success(token));
        };
        return successHandler;
//        return new AuthenticationSuccessHandler() {
//
//            @Override
//            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
//                                                Authentication authentication) throws IOException, ServletException {
//                SysUser loginUser = (SysUser) authentication.getPrincipal();
//
//                Token token = tokenService.saveToken(loginUser);
//                ResponseUtil.responseJson(response, HttpStatus.OK.value(), token);
//            }
//        };
    }

    /**
     * 登陆失败
     *
     * @return
     */
    @Bean
    public AuthenticationFailureHandler loginFailureHandler() {
        AuthenticationFailureHandler failureHandler = (HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) -> {
//            String msg;
//            if (exception instanceof BadCredentialsException) {
//                msg = "用户名或密码错误";
//            } else {
//                msg = exception.getMessage();
//            }
//            ResponseInfo info = new ResponseInfo(HttpStatus.UNAUTHORIZED.value() + "", msg);
            ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), R.fail(exception));
        };
        return failureHandler;
//        return new AuthenticationFailureHandler() {
//
//            @Override
//            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
//                                                AuthenticationException exception) throws IOException, ServletException {
//                String msg;
//                if (exception instanceof BadCredentialsException) {
//                    msg = "用户名或密码错误";
//                } else {
//                    msg = exception.getMessage();
//                }
//                ResponseInfo info = new ResponseInfo(HttpStatus.UNAUTHORIZED.value() + "", msg);
//                ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), info);
//            }
//        };

    }

    /**
     * 未登录，返回401
     *
     * @return
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        AuthenticationEntryPoint unLogin = (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) -> {
//            ResponseInfo info = new ResponseInfo(HttpStatus.UNAUTHORIZED.value() + "", "请先登录");
            ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), R.fail(ReturnEnum.USER_NOT_LOGGED_IN));
        };
        return unLogin;
//        return new AuthenticationEntryPoint() {
//
//            @Override
//            public void commence(HttpServletRequest request, HttpServletResponse response,
//                                 AuthenticationException authException) throws IOException, ServletException {
//                ResponseInfo info = new ResponseInfo(HttpStatus.UNAUTHORIZED.value() + "", "请先登录");
//                ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), info);
//            }
//        };
    }

    /**
     * 退出处理
     *
     * @return
     */
    @Bean
    public LogoutSuccessHandler logoutSussHandler() {
        LogoutSuccessHandler logoutSuccessHandler = (HttpServletRequest request, HttpServletResponse response, Authentication authentication) -> {
//            ResponseInfo info = new ResponseInfo(HttpStatus.OK.value() + "", "退出成功");

            String token = TokenFilter.getToken(request);
            tokenService.deleteToken(token);

            ResponseUtil.responseJson(response, HttpStatus.OK.value(), R.success("退出成功"));
        };
        return logoutSuccessHandler;
//        return new LogoutSuccessHandler() {
//
//            @Override
//            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
//                                        Authentication authentication) throws IOException, ServletException {
//                ResponseInfo info = new ResponseInfo(HttpStatus.OK.value() + "", "退出成功");
//
//                String token = TokenFilter.getToken(request);
//                tokenService.deleteToken(token);
//
//                ResponseUtil.responseJson(response, HttpStatus.OK.value(), info);
//            }
//        };
    }
}
